class CanvasDataWorkerManager {
    constructor() {
        this.worker = null;
        this.callbacks = new Map();
        this.messageId = 0;
    }

    // 初始化 Worker
    init() {
        if (this.worker) return;

        // 创建新的 Worker
        this.worker = new Worker(new URL('../workers/canvasDataWorker.js',
            import.meta.url));

        // 监听 Worker 消息
        this.worker.onmessage = (e) => {
            const { type, data, error, success, messageId } = e.data;

            // 查找对应的回调函数
            const callback = this.callbacks.get(messageId);
            if (callback) {
                if (success) {
                    callback.resolve(data);
                } else {
                    callback.reject(new Error(error));
                }
                this.callbacks.delete(messageId);
            }
        };

        // 监听 Worker 错误
        this.worker.onerror = (error) => {
            console.error('Worker error:', error);
            // 清理所有待处理的回调
            this.callbacks.forEach((callback) => {
                callback.reject(error);
            });
            this.callbacks.clear();
        };
    }

    // 序列化画布数据
    async serialize(canvasData) {
        return this._postMessage('serialize', canvasData);
    }

    // 反序列化画布数据
    async deserialize(serializedData) {
        return this._postMessage('deserialize', serializedData);
    }

    // 发送消息到 Worker
    _postMessage(type, data) {
        if (!this.worker) {
            this.init();
        }

        const messageId = this.messageId++;

        return new Promise((resolve, reject) => {
            // 存储回调函数
            this.callbacks.set(messageId, { resolve, reject });

            // 发送消息到 Worker
            this.worker.postMessage({
                type,
                data,
                messageId
            });
        });
    }

    // 终止 Worker
    terminate() {
        if (this.worker) {
            this.worker.terminate();
            this.worker = null;
            this.callbacks.clear();
        }
    }
}

// 创建单例实例
const canvasDataWorkerManager = new CanvasDataWorkerManager();

export default canvasDataWorkerManager;